package com.bangdream.michelia.presenter;


import android.app.Dialog;
import android.app.ProgressDialog;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.contract.UserContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.FinishedStateBean;
import com.bangdream.michelia.entity.STSBean;
import com.bangdream.michelia.entity.UserInfoBean;
import com.bangdream.michelia.entity.UserMsgBean;
import com.bangdream.michelia.model.IUserModelImpl;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.rejava.BaseObserverEntityNormalHttp;
import com.bangdream.michelia.tool.rejava.BaseObserverStringNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.TokenManagerDef;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.PublicResources;
import com.bangdream.michelia.utils.SPUtils;
import com.google.gson.Gson;

import java.util.Map;

/**
 * Created by Mr.Wang on 2018/3/30.
 * 909732184@qq.com
 * 用户信息相关的presenter
 */

public class UserPresenter<V> extends BasePresenter<V> {
    private static final String TAG = "UserPresenter";
    private UserContract.IUserModel model;
    public UserPresenter() {
        model = new IUserModelImpl();
    }

    /**
     * 获取验证码
     * @param phoneNumber 手机号
     */
    public void getVerificationCode(final UserContract.CodeType type, String phoneNumber, ProgressDialog dialog) {
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        model.getRegisterCode(type,phoneNumber)
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(this,dialog) {
                    @Override
                    public void onHandleSuccess(String stResult) {
                        try {
//                            BaseEntity<String> baseEntity = new Gson().fromJson(stResult,BaseEntity.class);
                            BaseEntity baseEntity = JSON.parseObject(stResult, BaseEntity.class);

//                            if(stResult.contains("Success")){
//                                iView.setRegisterCode(true, "发送成功");
//
//                            }else{
//                                iView.setRegisterCode(false, "发送失败");
//`
//                            }
                            if(baseEntity==null){
                                iView.setRegisterCode(false, "数据解析失败");
                                return;
                            }

                            if(baseEntity.isOk()) {
                                iView.setRegisterCode(true, baseEntity.getData().toString());
                            }else {
                                iView.setRegisterCode(false, baseEntity.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            if(stResult.contains("Success")){
                                iView.setRegisterCode(true, "");
                            }else{
                                iView.setRegisterCode(false, "");

                            }
//                            iView.setRegisterCode(false, "数据解析失败");
                        }
                    }
                });
    }


    /**
     * 注册
     * @param stCode   验证码
     * @param stPassword  密码
     * @param stPhone  手机号
     */
    public void actionRegister(String stCode,String stPhone,String stPassword) {
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        model.actionRegister(stCode,stPhone,stPassword)
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(this,pd) {
                    @Override
                    public void onHandleSuccess(String stResult) {
                        try {
                            BaseEntity baseEntity = new Gson().fromJson(stResult,BaseEntity.class);
                            if(baseEntity==null){
                                iView.actionRegister(false, "数据解析失败");
                                return;
                            }
                            if(baseEntity.isOk()) {
                                iView.actionRegister(true, "注册成功");
                            }else {
                                iView.actionRegister(false, baseEntity.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            iView.actionRegister(false, "数据解析失败");
                        }

                    }
                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setRegisterCode(false,message);
                    }
                });
    }

    /**
     * 找回密码
     * @param stCode   验证码
     * @param stPassword  密码
     * @param stPhone  手机号
     */
    public void actionFindPassword(String stCode,String stPhone,String stPassword) {
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        model.actionFindPassword(stPhone,stCode,stPassword)
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(this,pd) {
                    @Override
                    public void onHandleSuccess(String stResult) {
                        try {
                            BaseEntity baseEntity = new Gson().fromJson(stResult,BaseEntity.class);
                            if(baseEntity==null){
                                iView.actionRegister(false, "数据解析失败");
                                return;
                            }
                            if(baseEntity.isOk()) {
                                iView.actionRegister(true, "找回成功");
                            }else {
                                iView.actionRegister(false, baseEntity.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            iView.actionRegister(false, "数据解析失败");
                        }

                    }
                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setRegisterCode(false,message);
                    }
                });
    }

    /**
     * 验证码登录
     * @param stCode   验证码
     * @param stPhone  手机号
     */
    public void actionCodeLogin(String stCode,String stPhone) {
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        model.actionCodeLogin(stPhone,stCode)
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<UserInfoBean>(this,pd) {
                    @Override
                    public void onHandleSuccess(UserInfoBean bean) {
                        actionLoginSuccess(iView,bean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.actionLogin(false, null);
                    }
                });
    }

    /**
     * 登录
     * @param accountName
     * @param password
     */
    public void actionLogin(String accountName,String password,String stCode) {
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        model.actionLogin(accountName,password,stCode)
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<UserInfoBean>(this,pd) {
                    @Override
                    public void onHandleSuccess(UserInfoBean bean) {
                        actionLoginSuccess(iView,bean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.actionLogin(false, null);
                    }
                });
    }

    public void actionThirdLogin(String faceUrl, String nickName, String openId, String userType){
        final UserContract.IUserView iView = getMyView();
        if (iView == null)
            return;
        model.actionThirdLogin(faceUrl,nickName,openId,userType)
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<UserInfoBean>(this,pd) {
                    @Override
                    public void onHandleSuccess(UserInfoBean bean) {
                        actionLoginSuccess(iView,bean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.actionLogin(false, null);
                    }
                });
    }

    //登录成功后的操作同一调用
    private void actionLoginSuccess(UserContract.IUserView iView,UserInfoBean bean){
        if(iView==null)
            return;
        try {
            if(bean!=null) {
//                SPUtils.put(MainApplication.getContext(),"homeChoose","企业内训");
                SPUtils.put(MainApplication.getContext(), PublicResources.SpKeyUserToken,bean.getToken());
                SPUtils.put(MainApplication.getContext(), PublicResources.SpKeyUserInfo,bean.getUser().toString());
                iView.actionLogin(true, "登录成功");

            }else {
                iView.actionLogin(false, "未知错误：数据为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            iView.actionLogin(false, "数据解析失败");
        }
    }

    public void getUserInfo(String id,String token){
        final UserContract.IUserView iView = getMyView();
        if(iView==null)
            return;
        TokenManagerDef.work(() -> model.getUserMsg(id,token)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<UserMsgBean>(this,pd) {
                    @Override
                    public void onHandleSuccess(UserMsgBean bean) {
                        iView.setUserMsg(true, bean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setUserMsg(false, null);
                    }
                });

    }

    public void getSTS(String token){
        final UserContract.IUserPicView iView=(UserContract.IUserPicView) obtainView();
        if(iView==null)
            return;
        TokenManagerDef.work(() -> model.getSTS(token)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<STSBean>(this,pd) {
                    @Override
                    public void onHandleSuccess(STSBean bean) {
                        iView.setSTS(true, bean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setSTS(false, null);
                    }
                });
    }

    public void uploadPic(String url){

        final UserContract.IUserPicView iView=(UserContract.IUserPicView) obtainView();
        if(iView==null)
            return;

        model.uploadPic(AppCurrentUser.getInstance().getToken(),url)
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<BaseEntity>(this,pd) {

                    @Override
                    public void onHandleSuccess(BaseEntity baseEntity) {

                    }
                });
    }

    public void editUser(Map map, Dialog pd){

        final UserContract.IUserEditView iView=(UserContract.IUserEditView) obtainView();
        if(iView==null)
            return;
        setPd(pd);
//        TokenManagerDef.work(() ->
                model.editUser(map).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(null,pd){
                    @Override
                    public void onHandleSuccess(String t) {
                        iView.isSuccessed(true);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.isSuccessed(false);
                    }
                });
    }

    public void getFinishstate(){
        final UserContract.IFinishState iView = (UserContract.IFinishState)obtainView();
        if (iView == null)
            return;
        TokenManagerDef.work(() -> model.getFinishstate()).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<FinishedStateBean>(this, pd) {
                    @Override
                    public void onHandleSuccess(FinishedStateBean beanList) {
                        iView.setFinishState(true,beanList);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setFinishState(false,null);

                    }
                });

    }


    public UserContract.IUserView getMyView() {
        return (UserContract.IUserView) obtainView();
    }
}
